package influx

import (
	"strings"

	"github.com/chinahdkj/xorm"
	"gitee.com/dayu1985/framework/context"
)

func NewInfluxDB(uri string) *xorm.Engine {

	db, err := xorm.NewEngine("influxdb", uri)

	if err != nil {
		panic(err)
	}

	return db
}

func DefaultInfluxDB(c *context.Configuration) *xorm.Engine {

	db := c.INI.MustValue(context.SECTION_DATABASE, "influxdb")

	if db == "" {
		panic("未定义数据库...")
	}

	return NewInfluxDB(db)
}

var (
	escaper   = strings.NewReplacer(`,`, `\,`, `"`, `\"`, ` `, `\ `, `=`, `\=`)
	unescaper = strings.NewReplacer(`\,`, `,`, `\"`, `"`, `\ `, ` `, `\=`, `=`)
)

// UnescapeString returns unescaped version of in.
func UnescapeString(in string) string {
	if strings.IndexByte(in, '\\') == -1 {
		return in
	}
	return unescaper.Replace(in)
}

// String returns the escaped version of in.
func String(in string) string {
	return escaper.Replace(in)
}
